package pers.fulsun.es.test._04_search;

import java.io.IOException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.Stats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import pers.fulsun.es.test._01_ESClient;

public class _010_ESTest_Doc_Search_Stats {
  private static RestHighLevelClient client = _01_ESClient.getClient();

  public static void main(String[] args) throws IOException {
    // 构建查询的请求体
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 构建聚合查询方式
    sourceBuilder.aggregation(AggregationBuilders.stats("stats_age").field("age"));

    // 创建搜索请求对象
    SearchRequest request = new SearchRequest();
    request.indices("user");
    sourceBuilder.size(0);
    request.source(sourceBuilder);

    SearchResponse response = client.search(request, RequestOptions.DEFAULT);

    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("aggregations========>>");
    // 和之前不同的是这里需要getAggregations获取聚合后的数据
    Aggregations aggregations = response.getAggregations();
    //从查询结果中获取刚才定义的最大值的名称
    Stats stats = aggregations.get("stats_age");
    System.out.println("count:"+stats.getCount());
    System.out.println("min:"+stats.getMin());
    System.out.println("max:"+stats.getMax());
    System.out.println("avg:"+stats.getAvg());
    System.out.println("sum:"+stats.getSum());
    System.out.println("<<========");
    // 关闭客户端连接
    client.close();
  }
}
